import jwt from 'jsonwebtoken'
import config from '../config/appConfig'
// 白名单
const whiteList = [
    '/login',
    '/register'
]
export async function myJwt(ctx, next) {
    if(!whiteList.some(item => item === ctx.request.url)) {
        // 需要token校验
        console.log('中间件')
        try{
            let token = ctx.request.header.authorization
            console.log(123, token)
            const decoded = jwt.verify(token, config.secret)
            if (decoded && decoded.message) {
                console.log(123, decoded.message)
                // jwt有问题，响应
                ctx.body = {
                    code: 0,
                    msg: decoded.message
                }
            } else {
                // 没问题
                // 存储用户信息
                ctx.username = decoded.name
                await next()
            }
        }catch(e) {
            if(e.message === 'jwt expired') {
                ctx.body = {
                    code: 1001,
                    msg: '请重新登陆'
                }
            } else {
                ctx.body = {
                    code: 1001,
                    msg: e.message
                }
            }
        }
    } else {
        await next()
    }
}